package com.mote;

import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.util.Log;

public class MoteService extends Service {

	private NotificationManager mNotificationManager;

	HttpGet httpReq;
	HttpResponse httpRes;
	HttpClient httpClient;

	private Timer timer = new Timer();

	private WebService webService;
	private DBhelper dBhelper;
	private SharedPreferences mSettings;
	
	private int INTERVAL = 60*1000;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		mSettings = getSharedPreferences("mote", 0);
		
		webService = new WebService(this, mSettings);

		dBhelper = new DBhelper(this, mSettings, 0);
	}

	@Override
	public void onDestroy() {

	}

	@Override
	public void onStart(Intent intent, int startid) {
		timer.scheduleAtFixedRate(new TimerTask() {

			@Override
			public void run() {
				int sync = mSettings.getInt("sync", 0);
				
				if (sync == 0) {
					Log.e("mote", "first_sync is false");
					
					return;
				}
				
				sync();
			}

		}, 0, INTERVAL);
	}

	private void sync() {
		int newmote = 0;
		
		//
		try {

			String motes = webService.sync();
			
			//
			if ("".equals(motes)) {
				return;
			}

			String[] lines = motes.split("\002");

			newmote = lines.length;

			for (int i = 0; i < lines.length; i++) {
				dBhelper.insertData(Integer.parseInt(lines[i].split("\001")[0]),
						lines[i].split("\001")[1], lines[i].split("\001")[2]);
			}
			
			// 设置notification的参数
			int icon = R.drawable.mote;
			CharSequence tickerText = "有" + newmote + "个新mote";
			long when = System.currentTimeMillis();

			Notification notification = new Notification(icon, tickerText, when);

			notification.flags |= Notification.FLAG_AUTO_CANCEL;

			//
			Context context = getApplicationContext();
			CharSequence contentTitle = "新mote";
			CharSequence contentText = "有" + newmote + "个新mote";

			//
			Intent notificationIntent = new Intent(this, Mote.class);

			PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
					notificationIntent, 0);

			//
			notification.setLatestEventInfo(context, contentTitle, contentText,
					contentIntent);

			mNotificationManager.notify(0, notification);
		} catch (Exception e) {
			e.getMessage();
		}
	}
}